package jsyf.oa.web.wechat.service_account.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.ResponseUtils;
import jsyf.oa.facade.wechat.service_account.WechatQRCodeFacade;
import jsyf.oa.facade.wechat.service_account.WechatUserFacade;
import jsyf.oa.web.wechat.service_account.utils.CommonUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Api(value = "服务号-获取二维码", description = "服务号-获取二维码")
@Controller
@RequestMapping(value = "/QRCode")
public class QRCodeController {

    @Resource
    private WechatQRCodeFacade wechatQRCodeFacade;

    @Resource
    private WechatUserFacade wechatUserFacade;
    /**
     * 服务号-获取二维码
     */
    @ApiOperation(
            value = "获取微信推广二维码",
            notes = "获取微信推广二维码",
            httpMethod = "POST",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "{\"customerTel\":\"15800000000\",\"salerId\":\"2017121820474C54BC85A65DEC9B455A\"}\ncustomerTel-客户手机号；salerId-销售经理userId", dataType = "String", paramType = "body")
    @RequestMapping(value = "/getQRCodeBycustomerTel.json", method = RequestMethod.POST)
    public void sendMessage(HttpServletResponse response, @RequestBody String jsonData) {


        JSONObject telJsonObject = (JSONObject) JSONObject.parse(jsonData);
        String customerTel = telJsonObject.getString("customerTel");
        if (customerTel==null || customerTel.length() == 0){
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("客户手机号码未填写"));
            return;
        }else if (!CommonUtil.isChinaPhoneLegal(customerTel)){
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("客户手机号码格式不正确"));
            return;
        }else if (wechatUserFacade.isExitByCustomerTel(customerTel)){//   客户已关注且手机号已绑定
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("客户手机号码已绑定"));
            return;
        }

        JSONObject jsonObject = wechatQRCodeFacade.getQRCode(jsonData);
        String ticket = jsonObject.getString("ticket");
        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
        JSONObject result = new JSONObject();
        result.put("url",url);
        if (jsonObject != null) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjTimeRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }
}
